import {combineReducers} from 'redux'
import actionTypes from './types'
import {getRedirectPath} from '../utils/index'

let initUser = {
    username: '',
    type: '',
    msg: '',
    redirectTo: ''
}

function user(state = initUser, action) {
    switch (action.type) {
        case actionTypes.AUTH_SUCCESS:

            let redirectTo = getRedirectPath(action.data.type, action.data.header)
            return {...action.data, redirectTo: redirectTo}
        case actionTypes.ERROR_MSG:
            return {...state, msg: action.data}
        case actionTypes.RECEVITE_USER: // 接收用户
            return action.data
        case actionTypes.RESET_USER: // 重置用户
            return {...initUser, msg: action.data}
        default:
            return state
    }

}

const initUserList = []

function userList(state = initUserList, action) {
    switch (action.type) {
        case actionTypes.RECEVITE_USER_LIST:
            return action.data
        default:
            return state
    }
}

const initChat = {
    chatMsgs: [],
    users: {},
    unReadCount: 0
}

function chat(state = initChat, action) {
    switch (action.type) {
        case actionTypes.RECEVITE_MAG:
            var {chatMsg, userid} = action.data
            return {
                chatMsgs: [...state.chatMsgs, chatMsg],
                users: state.users,
                unReadCount: state.unReadCount + (!chatMsg.read && chatMsg.to === userid ? 1 : 0)
            }
        case actionTypes.RECEVITE_MSG_LIST:
            var {chatMsgs, users} = action.data
            return {
                chatMsgs,
                users,
                unReadCount: chatMsgs.reduce((preTol, msg) => preTol + (!msg.read && msg.to === action.data.userid ? 1 : 0),0)
            }

        case actionTypes.MSG_READ:
            const {from, to, count} = action.data

            state.chatMsgs.forEach(msg => {
                if(msg.from===from && msg.to===to && !msg.read) {
                    msg.read = true
                }
            })
            return {
                users: state.users,
                chatMsgs: state.chatMsgs.map(msg => {
                    if(msg.from===from && msg.to===to && !msg.read) { // 需要更新
                        return {...msg, read: true}
                    } else {// 不需要
                        return msg
                    }
                }),
                unReadCount: state.unReadCount-count
            }
        default:
            return state
    }
}

export default combineReducers({
    user,
    userList,
    chat
})